import { createRouter, createWebHashHistory } from 'vue-router'
import Layout from '@/layout'
import store from '@/store'

// 公共路由
const publicRoutes = [
  {
    path: '/login',
    component: () => import('@/views/login/index'),
    hidden: true
  },
  {
    path: '/register',
    component: () => import('@/views/register/index'),
    hidden: true
  },
  {
    path: '/',
    component: Layout,
    redirect: '/dashboard',
    children: [
      {
        path: 'dashboard',
        component: () => import('@/views/dashboard/index'),
        name: 'Dashboard',
        meta: { title: '首页', icon: 'HomeFilled' }
      }
    ]
  },
  {
    path: '/profile',
    component: Layout,
    hidden: true,
    children: [
      {
        path: 'index',
        component: () => import('@/views/profile/index'),
        name: 'Profile',
        meta: { title: '个人中心' }
      }
    ]
  }
]

// 动态路由，根据用户权限动态加载
const asyncRoutes = [
  {
    path: '/system',
    component: Layout,
    redirect: '/system/user',
    name: 'System',
    meta: { title: '系统管理', icon: 'Setting', roles: ['admin'] },
    children: [
      {
        path: 'user',
        component: () => import('@/views/system/user/index'),
        name: 'User',
        meta: { title: '用户管理', icon: 'User', roles: ['admin'] }
      },
      {
        path: 'role',
        component: () => import('@/views/system/role/index'),
        name: 'Role',
        meta: { title: '角色管理', icon: 'UserFilled', roles: ['admin'] }
      },
      {
        path: 'menu',
        component: () => import('@/views/system/menu/index'),
        name: 'Menu',
        meta: { title: '菜单管理', icon: 'Menu', roles: ['admin'] }
      }
    ]
  },
  // {
  //   path: '/video',
  //   component: Layout,
  //   redirect: '/video/parse',
  //   name: 'Video',
  //   meta: { title: '视频解析', icon: 'VideoCamera' },
  //   children: [
  //     {
  //       path: 'parse',
  //       component: () => import('@/views/video/parse/index'),
  //       name: 'VideoParse',
  //       meta: { title: '视频解析', icon: 'VideoPlay' }
  //     },
  //     {
  //       path: 'history',
  //       component: () => import('@/views/video/history/index'),
  //       name: 'VideoHistory',
  //       meta: { title: '解析历史', icon: 'List' }
  //     },
  //     {
  //       path: 'stats',
  //       component: () => import('@/views/video/stats/index'),
  //       name: 'VideoStats',
  //       meta: { title: '解析统计', icon: 'DataAnalysis', roles: ['admin'] }
  //     }
  //   ]
  // },
  // 404页面必须放在最后
  { path: '/:pathMatch(.*)*', redirect: '/404', hidden: true }
]

const router = createRouter({
  history: createWebHashHistory(),
  routes: publicRoutes,
  scrollBehavior: () => ({ top: 0 })
})

// 白名单路由
const whiteList = ['/login','/register']

// 路由守卫
router.beforeEach(async (to, from, next) => {
  // 获取token
  const token = store.getters.token
  
  if (token) {
    // 已登录且要跳转的是登录页
    if (to.path === '/login') {
      next({ path: '/' })
    } else {
      // 判断当前用户是否已拉取完user_info信息
      const hasRoles = store.getters.roles && store.getters.roles.length > 0
      if (hasRoles) {
        next()
      } else {
        try {
          // 获取用户信息
          const { roles } = await store.dispatch('user/getInfo')
          
          // 根据roles权限生成可访问的路由表
          const accessRoutes = await store.dispatch('permission/generateRoutes', roles)
          
          // 动态添加可访问路由表
          accessRoutes.forEach(route => {
            router.addRoute(route)
          })
          
          // 设置replace: true，这样导航就不会留下历史记录
          next({ ...to, replace: true })
        } catch (error) {
          // 移除token并跳转登录页面
          await store.dispatch('user/logout')
          next(`/login?redirect=${to.path}`)
        }
      }
    }
  } else {
    // 未登录可以访问白名单页面
    if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      // 否则全部重定向到登录页
      next(`/login?redirect=${to.path}`)
    }
  }
})

export { publicRoutes, asyncRoutes }
export default router